import asyncio
import logging
from pathlib import Path


logger = logging.getLogger(__name__)


async def sync_db_table():
    """同步数据库表结构"""
    from alembic.command import revision, upgrade
    from alembic.config import Config

    try:
            from src.database import AsyncSessionLocal
            print('清理数据库中的版本')
            async with AsyncSessionLocal() as session:
                from sqlalchemy import text
                try:
                    res = await session.execute(text('delete from alembic_version'))
                    print('清理版本结果:', res.__dict__)
                    await session.commit()
                except Exception as e:
                    print('清理版本失败', e)
            for file in Path('alembic/versions').glob("*.py"):
                file.unlink(missing_ok=True)
            config = Config('alembic.ini')
            print('开始生成表结构差异数据.')
            scripts = revision(config=config, autogenerate=True)
            print(f'生成表结构差异数据成功({scripts}),开始同步结构信息到数据库')
            upgrade(config=config, revision='head')
            print('同步数据库表结构完成.')
    except Exception as e:
        print('更新表结构失败', e)


asyncio.run(sync_db_table())
